#!/usr/bin/env bash

# niro@sdf

# The wrapped command $() has several parts to it so I've described 
# what each part does below.

# L32 Scrape url quietly with 5 second timeout
# L33 Remove newlines
# L34 Remove leading whitespace and remove first occurance of <h3>
# L35 Squash all spaces to single spaces
# L36 Use <h3> as delimeter and print $1 column
# L37 Strip all HTML tags
# L38 Cut output to IRC acceptable maximum (first 512 characters)

source '../say.sh'

nick="$1"
chan="$2"
args=("${@:3}")
req="${args[0]}"

if [[ "${#args[@]}" -ge 2 && "${args[-2]}" = '>' &&
    ! "${args[-1]}" =~ '#' ]]; then
    chan="${args[-1]}"
fi

regex='^[1-9]$'
stat='http://status.sdf.org/ (hosted independently)'

scrape() {
    wget -T 5 -qO - http://status.sdf.org |\
    tr -d '\n' |\
    sed -e '/^[[:blank:]]*$/d; s/^<h3>//;' |\
    tr -s ' ' |\
    awk -F'<h3>' -v i="$1" '{print $i}' |\
    sed -e 's/<[^>]*>/ /g' |\
    cut -c1-512
}

if [[ "$req" =~ $regex ]]; then
    body="$(scrape "$req")"
else
    body="$(scrape 1)"
fi

if [[ -z "$body" ]]; then
    say "$chan" "Could not scrape status information from $stat."
else
    say "$chan" "*$body*" "scraped from $stat."
fi

